<?php
#!/usr/bin/php
    header("Content-Type: text/html; charset=utf-8") ;
    set_time_limit(0);
    date_default_timezone_set('PRC'); 
    error_reporting(0);
    
    $con = mysql_connect("101.37.76.105","root","eaifxwaihui");
    if (!$con) { die('Could not connect: ' . mysql_error());  }
    mysql_select_db("waihui", $con);

    

    //连胜单数
    $LIANSHENG=5;  
    //连败单数
    $LIANBAI=3  ;
    //交易高手
    $GAOSHOU=30  ;
    //分析专家
    $ZHUANJIA=50 ;
    //操盘大师 
    $DASHI=70 ;
    //金融宗师  
    $ZONGSHI=100;
    //前3单给钱  
    $QIANJIDAN=3 ;
    //定级单数 
    $DINGJINUM=30 ;
   
    $starttime  = strtotime(date("Y-m-d H:i:s",mktime(6,0,0,date("m"),date("d")-date("w")+(date("w")==0?-6:1),date("Y")))); //周一早上6:00:00
    $endtime    = strtotime(date("Y-m-d H:i:s",mktime(5,5,0,date("m"),date("d")-date("w")+(date("w")==0?-1:6),date("Y")))); //周六早上5:05:00
    $currenttime = time();
	

    if($starttime > $currenttime){
        return false;
    }else if($endtime+3600 < $currenttime){
        return false;
    }
    
    //定时执行
    for ( $i = 0;$i < 120;$i++){       
        
        //如果此时的时间是周六早上的5:05，那么把明日之星的未平仓的单子，全部平仓，认证的分析师不平
        if($currenttime >= $endtime){			
            //$aa = mysql_query("SELECT o.* INTO OUTFILE '/data.txt' FIELDS TERMINATED BY ',' FROM waihui_order o inner join waihui_member m where o.tel = m.tel and o.isstop=1 and ispersonal=0 and m.isanalyst != 1");
            $query = 'select o.*,m.id as memid from waihui_order o inner join waihui_member m on o.tel = m.tel and o.isstop=1 and ispersonal=0 and m.isanalyst != 1';
            $list=mysql_query($query);
            
            file_put_contents("order.txt",'');
        }else{
            $query = "select o.*,m.id as memid from waihui_order o inner join waihui_member m on o.tel = m.tel where o.isstop=1 and o.ispersonal=0";
            $list=mysql_query($query);
        }
        //print_r($list);die();
        if($list){
          
            $url = "http://db2015.wstock.cn/wsDB_API2/stock.php?market=FX&u=liyunhe1228&p=liyunhe1228&r_type=2&num=200";
            $contents = file_get_contents("compress.zlib://".$url);
            file_put_contents("test.txt",$contents.time());
            $res=json_decode($contents);
            
            while($lval = mysql_fetch_assoc($list)){
		//print_r($lval);exit;
                foreach ($res as $rkey=>$rval){
                    $istrue = 0;
                    $data   = [];
                    $tel    = $lval['tel'];
                    $tradeid = $lval['tradeid'];
                    
                    
                    if($currenttime >= $endtime){  	//周六强制平仓
                      
                        
                    
                        if(substr($rval->Symbol,2) == $lval['typename']){                         
                            if($lval['buy_status'] == 1){ //1:买空，卖出
                                $data['end_point']    = $rval->BP1;
								//echo $lval['begin_point'].'-----'.$data['end_point'];
                                $data['final_point']  = $lval['begin_point']-$data['end_point'];
                            }else{ //0:买多
                                $data['end_point']    = $rval->SP1;
								//echo $data['end_point']."-----".$lval['begin_point'];
                                $data['final_point']  = $data['end_point']-$lval['begin_point'];
                            }
							$data['stop_status'] = 2;
                        }else{
                            continue;
                        }
							
                    }else if(substr($rval->Symbol,2) == $lval['typename']){  //扫损,先发报文，然后执行平仓操作
                        
                        
                        
                        
						
                        //$rval->BP1：卖出 ，$rval->SP1：买入
                        //if(substr($rval->Symbol,2) == $lval['typename']){  
                            if($lval['buy_status'] == 1){ //1:买空，卖出

                                if($lval['target_loss_point'] < $rval->BP1){
                                    $data['end_point']    = $lval['target_loss_point'];
                                    $data['final_point']  = $lval['begin_point']-$data['end_point'];
                                }else if($lval['target_profit_point'] > $rval->BP1){
                                    $data['end_point']  = $lval['target_profit_point'];
                                    $data['final_point']  = $lval['begin_point']-$data['end_point'];
                                }else if($lval['target_loss_point']   == $rval->BP1){
                                    $data['end_point']  = $lval['target_loss_point'];
                                    $data['final_point']  = $lval['begin_point']-$data['end_point'];
                                }else if($lval['target_profit_point'] == $rval->BP1){
                                    $data['end_point']  = $lval['target_profit_point'];
                                    $data['final_point']  = $lval['begin_point']-$data['end_point'];
                                }else{
                                    continue;
                                }
                                
                            }else{ //0:买多

                                if($lval['target_loss_point'] > $rval->SP1){
                                    $data['end_point']    = $lval['target_loss_point'];
                                    $data['final_point']  = $data['end_point']-$lval['begin_point'];
                                }else if($lval['target_profit_point'] < $rval->SP1){
                                    $data['end_point']  = $lval['target_profit_point'];
                                    $data['final_point']  = $data['end_point']-$lval['begin_point'];
                                }else if($lval['target_profit_point'] == $rval->SP1){
                                    $data['end_point']  = $lval['target_profit_point'];
                                    $data['final_point']  = $data['end_point']-$lval['begin_point'];
                                }else if($lval['target_loss_point'] == $rval->SP1){
                                    $data['end_point']    = $lval['target_loss_point'];
                                    $data['final_point']  = $data['end_point']-$lval['begin_point'];
                                }else{
                                    continue;
                                }
                            }
                            $data['stop_status']=1;
                    }else{
			continue;
                    }  
					
                    if($currenttime < $endtime){  	//如果是扫损，那么发送报文

                        $host="101.37.76.105";
                        $port=8099;
                        //创建一次 实现多次通信
                        $socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socket\n");
                        $conn=socket_connect($socket,$host,$port) or die("cannot connect server\n");
                        socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 10);
                        /* 发送报文start */
                        $followsql     = 'select * from waihui_follow where  analyst_id='.$lval['memid'].' and status = 1';
                        $isexistfollow = mysql_query($followsql);
                        if(mysql_fetch_row($isexistfollow)){ //当资源不为空
                                $infodata="{   
                                        head: {
                                          account: '$tel',
                                          tradecode: 8803,
                                          allsend:0
                                        },
                                        body: {
                                                fromsource: 'netpage',
                                                trader_orderid : '$tradeid',
                                        }
                                }&";
                                //echo $infodata;
                                socket_write($socket,$infodata) or die("cannot write data\n");
                                $infoResult   =socket_read($socket,1024,PHP_BINARY_READ);
                                $infoSubstr   = substr($infoResult, 0 ,  (strlen($infoResult)-1));
                                $info         = json_decode($infoSubstr,true);

                                file_put_contents("close.txt",'扫损时间：'.date('Y-m-d H:i:s').$infodata.'返回报文状态值：'.$info['ret_code'],FILE_APPEND);
                                if($info['ret_code'] != '0000'){
                                        continue;
                                }
                        }

                        /* 发送报文end */
                    }	
					
                    if($lval['typename'] == 'XAUUSD'){   //黄金数据类型点位计算
                        $data['final_point'] = round(($data['final_point']*10-10),2);

                    }else if($lval['typename'] == 'NYOL20'){
                        $data['final_point'] = round(($data['final_point']*100-10),2);
                    }else if(stripos($lval['typename'],'JPY')){
                        $data['final_point'] = round(($data['final_point']*100-10),2);
                    }else{

                        $data['final_point'] = round(($data['final_point']*10000-10),2);
                    }

                    $data['trade_status'] = $data['final_point'] >0?1:0;
                      //print_r($data);    
                        
                        $query1 = "select grade,alltraid,liansheng,lianbai,star,authstatus,isanalyst from waihui_member where tel='$tel'";
                        $memberInfo = mysql_query($query1);
                        if($memberInfo){
                            $memberInfo = mysql_fetch_assoc($memberInfo);
                            
                            if($memberInfo['grade'] != '-1'){  //如果用户已定级
                              
                                if($data['trade_status'] > 0){  //如果当前订单是盈利的，那么连胜字段+1，连败字段=0
                                    $sql3 = "update waihui_member set alltraid=alltraid+1,liansheng=liansheng+1,lianbai=0 where tel='$tel'";
                                }else{  //如果当前订单是亏损的，那么连败字段+1，连剩字段=0
                                    $sql3 = "update waihui_member set alltraid=alltraid+1,lianbai=lianbai+1,liansheng=0 where tel='$tel'";
                                }
                                
                               
                                //根据用户的等级定奖金
                                $todayBeginTime=mktime(0,0,0,date('m'),date('d'),date('Y'));
                                if($data['final_point'] > 10 && $memberInfo->authstatus == 2 && $memberInfo->isanalyst == 1){  //盈利大于10个点
                                  
                                    //用户今天已平仓的单数,如果小于3单，那么有奖励，否则没有
                                    //$sql2 = "select count(id) as sum from waihui_order where tel='$tel' and trade_status='1' and ispersonal=0 and isstop=0 and end_time>'$todayBeginTime'";
                                    $sql2 = "select count(id) as sum from waihui_order where tel='$tel' and ispersonal=0 and isstop=0 and end_time>'$todayBeginTime'";
                                    $res2 = mysql_query($sql2);
                                    $sum = mysql_fetch_assoc($res2);
                                    if($sum && $sum['sum'] < $QIANJIDAN){  
                                        if($memberInfo['grade'] == 0 || $memberInfo['grade'] == -1){  
                                            $data['money'] = 0;
                                        }else if($memberInfo['grade'] == 1){
                                            $data['money']=  $GAOSHOU;
                                        }else if($memberInfo['grade'] == 2){
                                            $data['money']=  $ZHUANJIA;
                                        }else if($memberInfo['grade'] == 3){
                                            $data['money']=  $DASHI;
                                        }else if($memberInfo['grade'] == 4){
                                            $data['money']=  $ZONGSHI;
                                        }
                                    }else{
                                        $data['money'] = 0;
                                    }
                                 
                                   
                                }else{
                                    $data['money'] = 0;
                                }

                            }else{  //如果用户没有定级
                                $data['money'] = 0;
                                $sql3 = "update waihui_member set alltraid=alltraid+1 where tel='$tel'";
                            }
                            
                            
                            $updateAlltrade = mysql_query($sql3);
                          
                            if(!$updateAlltrade){
                                return json_encode(array('status'=>0));   //数据有错
                            }
                            
                            //更新完数据后，重新查询新数据
                            $queryChongXin = "select grade,alltraid,liansheng,lianbai,star from waihui_member where tel='$tel'";
                            $userInfo = mysql_query($queryChongXin);
                            if($userInfo){
                                $userInfo = mysql_fetch_array($userInfo);
                            } 

                            $user = '';
                            
                            if($userInfo && $userInfo['alltraid'] == $DINGJINUM){  //当用户喊单量=30单，给用户定级
                                $prifitSum = "select count(id) as num from waihui_order where tel='$tel' and trade_status='1' and ispersonal=0 and isstop=0";
                                
                                $prifitSum = mysql_query($prifitSum);
                                $prifitSum = mysql_fetch_assoc($prifitSum);
                                if($prifitSum){
                                    if($prifitSum['num'] <= 14){  //0-14单
                                        $user['grade'] = '0';
                                        $user['star'] = '0';
                                    }else if($prifitSum['num'] >= 15 && $prifitSum['num'] <= 19){  //15-19单
                                        $user['grade'] = '1';
                                        $user['star'] = '1';
                                    }else if($prifitSum['num'] >= 20 && $prifitSum['num'] <= 24){  //20-24单
                                        $user['grade'] = '2';
                                        $user['star'] = '1';
                                    }else if($prifitSum['num'] >= 25 && $prifitSum['num'] <= 30){  //25-30单
                                        $user['grade'] = '3';
                                        $user['star'] = '1';
                                    }
                                }
                                $user['liansheng'] = 0;
                                $user['lianbai'] = 0;
                                
                               
                              
                              
                                $update_member =mysql_query( "update waihui_member set grade='".$user['grade']."',star='".$user['star']."',liansheng=".$user['liansheng'].",lianbai=".$user['lianbai']." where tel='$tel'");
                               
                               
                                if(!$update_member){
                                    return json_encode(array('status'=>0));   //数据错误
                                }                                    
                            }else if($userInfo && $userInfo['alltraid'] > $DINGJINUM){  //如果用户已定级
                               
                                $user['liansheng'] = $userInfo['liansheng'];  //防止更新数据库时，没有值，先取数据中的值作为默认值
                                $user['lianbai'] = $userInfo['lianbai'];
                                $user['grade'] = $userInfo['grade'];
                                $user['star'] = $userInfo['star'];

                                if($userInfo['grade'] == 0){  //如果用户段位是喊单能手，即 0-14单正确
                                  
                                    if($userInfo['liansheng'] >= $LIANSHENG){  //如果用户连胜5单
                                        $user['grade'] = '1';
                                        $user['star'] = '1';
                                        $user['liansheng'] = 0;
                                    }

                                }else if($userInfo['grade'] == 1){  //如果用户段位是交易高手，即 15-19单正确
                                  
                                    if($userInfo['liansheng'] >= $LIANSHENG){  //如果用户连胜5单
                                       
                                        if($userInfo['star'] < 3){
                                           
                                            $aa = $userInfo['star'] + 1;
                                            $user['star'] = "$aa";
                                        }else if($userInfo['star'] == 3){
                                           
                                            $user['grade'] = '2';
                                            $user['star'] = '1';
                                        }

                                        $user['liansheng'] = 0;
                                    }else if($userInfo['lianbai'] >= $LIANBAI){
                                        if($userInfo['star'] > 1){
                                            $bb=$userInfo['star'] - 1;
                                            $user['star'] = "$bb";
                                        }else{
                                            $user['grade'] = '0';
                                            $user['star'] = '0';
                                        }
                                        $user['lianbai'] = 0;
                                    }

                                }else if($userInfo['grade'] == 2){  //如果用户段位是分析专家，即 20-24单正确
                                    if($userInfo['liansheng'] >= $LIANSHENG){  //如果用户连胜5单
                                        if($userInfo['star'] < 3){
                                            $aa = $userInfo['star'] + 1;
                                            $user['star'] = "$aa";
                                        }else if($userInfo['star'] == 3){
                                            $user['grade'] = '3';
                                            $user['star'] = '1';
                                        }
                                        $user['liansheng'] = 0;
                                    }else if($userInfo['lianbai'] >= $LIANBAI){
                                        if($userInfo['star'] > 1){
                                            $bb = $userInfo['star'] - 1;
                                            $user['star'] = "$bb";
                                        }else{
                                            $user['grade'] = '1';
                                            $user['star'] = '3';
                                        }
                                        $user['lianbai'] = 0;
                                    }
                                }else if($userInfo['grade'] == 3){  //如果用户段位是操盘大师，即 25-30单正确
                                    if($userInfo['liansheng'] >= $LIANSHENG){  //如果用户连胜5单
                                        if($userInfo['star'] < 3){
                                            $aa = $userInfo['star'] + 1;
                                            $user['star'] = "$aa";
                                        }else if($userInfo['star'] == 3){
                                            $user['grade'] = '4';
                                            $user['star'] = '1';
                                        }
                                        $user['liansheng'] = 0;
                                    }else if($userInfo['lianbai'] >= $LIANBAI){
                                        if($userInfo['star'] > 1){
                                            $bb = $userInfo['star'] - 1;
                                            $user['star'] = "$bb";
                                        }else{
                                            $user['grade'] = '2';
                                            $user['star'] = '3';
                                        }
                                        $user['lianbai'] = 0;
                                    }
                                }else if($userInfo['grade'] == 4){  //如果用户段位是金融大师
                                    if($userInfo['liansheng'] >= $LIANSHENG){  //如果用户连胜5单
                                        if($userInfo['star'] < 3){
                                            $aa = $userInfo['star'] + 1;
                                            $user['star'] = "$aa";
                                            $user['liansheng'] = 0;
                                        }
            //                                    else if($userInfo->star == 3){
            //                                        $user['grade'] = 4;
            //                                        $user['star'] = 0;
            //                                    }
                                    }else if($userInfo['lianbai'] >= $LIANBAI){
                                        if($userInfo['star'] > 1){
                                            $bb = $userInfo['star'] - 1;
                                            $user['star'] = "$bb";
                                        }else{
                                            $user['grade'] = '3';
                                            $user['star'] = '3';
                                        }
                                        $user['lianbai'] = 0;
                                    }
                                }
                            
                            

                                if($user != ''){  //更新用户的等级
                                    $updateGradeSql = "update waihui_member set grade='".$user['grade']."',star='".$user['star']."',liansheng=".$user['liansheng'].",lianbai=".$user['lianbai']." where tel='$tel'";
                                
                                    $updateResult =mysql_query($updateGradeSql);
                                    //$update_member = DB::table('waihui_member')->where('id',$session_data['id'])->update($user);
                                    if(!$updateResult){
                                        return json_encode(array('status'=>0));   //数据错误
                                    }  
                                }
                            }
                            
//                            if($istrue){  //更新订单表
                                $data['end_time']  = strtotime('now');
                                $data['isstop']    = 0;
                                //$data['stop_status'] = 1;
                            //print_r($data);    
                                $updateOrder = "update waihui_order set end_time='".$data['end_time']."' , isstop =0 , final_point=".$data['final_point'].", stop_status='".$data['stop_status']."' , end_point=".$data['end_point']." , trade_status='".$data['trade_status']."' , money=".$data['money']." where tradeid='".$lval['tradeid']."' and  tel=".$tel;
                               //echo $updateOrder.'<br/>';
                                $queryResult = mysql_query($updateOrder);
                                
                                $updateJifen = "update waihui_member set jifen=jifen+".$data['money']." where tel='".$tel."'";
                                $JifenResult = mysql_query($updateJifen);
                                
                                if(!$queryResult || !$JifenResult){
                                    return json_encode(array('status'=>0));   //数据有错
                                }
//                            }
                            
                        }else{
                            return json_encode(array('status'=>0));   //数据有错
                        }
                    }
                }
            }
        //sleep(3);
        usleep(500000);//暂停时间（单位为微秒） 0.5s
   }
    mysql_close($con);
